package com.neusoft.databus.policy.event;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.neusoft.bizcore.web.utils.JsonUtils;
import com.neusoft.databus.common.bean.ResourceBean;
import com.neusoft.databus.policy.constants.DatabusPolicyConstant;
import com.neusoft.databus.policy.model.Event;
import com.neusoft.databus.policy.model.Policy;
import com.neusoft.databus.policy.utils.PolicyUtil;

/**
 * 事件处理器
 * 
 * @author naxiang
 */
public abstract class PolicyEventHandler {
    private static Map<String, Object> lockPool = Maps.newConcurrentMap();
    protected static String cacheName = DatabusPolicyConstant.POLICY_EVENT_CACHE_NAME;

    public synchronized Object getLockInstance(String resourcecode) {
        Object storageLock = lockPool.get(resourcecode);
        if (storageLock == null) {
            lockPool.put(resourcecode, new Object());
        }
        return lockPool.get(resourcecode);
    }

    protected Event getEvent(Policy policy, String resourceCode) {
        Event event = new Event();
        event.setCode(PolicyUtil.getEventCode(resourceCode, policy.getCode()));
        event.setResourceCode(resourceCode);
        event.setPolicy(policy);
        return event;
    }

    /**
     * 告警提示信息
     * 
     * @param resourceCode
     * @param content
     * @return
     */
    protected String eventContent(String resourceCode, String content) {
        Map<String, Object> contentMap = JsonUtils.jsonToMap(content);
        return contentMap.get("0").toString().replace("#resourceCode#", resourceCode + "");
    }

    /**
     * 产生告警事件
     * 
     * @param resourceBean
     * @param time
     * @param policy
     * @param expressionTrueSquence
     */
    public abstract void trigger(ResourceBean resourceBean, Date time, Policy policy,
            List<Integer> expressionTrueSquence);

    /**
     * 解除告警事件
     * 
     * @param resourceBean
     * @param time
     * @param policy
     */
    public abstract void fixed(ResourceBean resourceBean, Date time, Policy policy);

}
